<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax函数</title>
    <style>
        .wrap{
            width: 600px;
            height: 600px;
            border: 2px solid darkorange;
            margin: 20px auto;
        }
        .wrap > .btn{
            margin: 10px 230px;
        }
        .wrap > .list{
            width: 400px;
            height: 500px;
            margin: 20px auto;
            border: 2px solid red;
            overflow: auto;
        }
    </style>
</head>
<body>
    <div class="wrap">
        <button class="btn">获取数据</button>
        <ul class="list"></ul>
    </div>

    <script>
        const list = document.querySelector('.wrap > .list');
        const btn = document.querySelector('.wrap > .btn');

        const url = 'https://api.apiopen.top/api/sentences';

        btn.addEventListener('click',() => {
            ajax('GET',url,(data)=>{
                const li = document.createElement('li');
                li.innerHTML = `题目：${data.result.from}<br>`;
                li.innerHTML += `内容：${data.result.name}<br><br>`;
                list.appendChild(li);
            })
        })

        function ajax(method,url,fun){
            const xhr = new XMLHttpRequest();
            xhr.open(method,url,true);
            xhr.responseType = 'json';
            xhr.addEventListener('load',()=>{
                if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304){
                    console.log('请求成功！');
                    console.log(xhr.response);
                    fun(xhr.response);
                }
            })
            xhr.send();
        }

    </script>
</body>
</html>